package config

import (
	"os"
	"os/exec"
	"path/filepath"
	"sync"

	"gopkg.in/yaml.v3"
)

var Conf *GitConfig

type GitConfig struct {
	Dir              string `yaml:"dir"`
	ScriptType       string `yaml:"scriptType"`
	DefaultBranch    string `yaml:"defaultBranch"`
	MaxDiffFiles     int    `yaml:"maxDiffFiles"`
	MaxDiffLines     int    `yaml:"maxDiffLines"`
	MaxDiffLineChars int    `yaml:"maxDiffLineChars"`
	DiffTimeOut      int    `yaml:"diffTimeOut"`
	LocalPath        string `yaml:"localPath"`
	ExternalURL      string `yaml:"externalURL"`
	Addr             string `yaml:"addr"`
	GitBinaryPath    string `yaml:"gitBinaryPath"`
	Auth             Auth   `yaml:"auth"`
	ANSICharset      string `yaml:"ANSICharset"`
}

type Auth struct {
	APIEndpoint string `json:"authEndpoint"`
}

var (
	CustomConf  string
	appPath     string
	appPathOnce sync.Once
)

func Init(path string) {
	Conf = &GitConfig{}
	content, err := os.ReadFile(path)
	if err != nil {
		panic("read config file: " + err.Error())
	}
	err = yaml.Unmarshal(content, Conf)
	if err != nil {
		panic("unmarshal config file: " + err.Error())
	}

	// 执行系统命令，防止中文乱码问题
	exec.Command("git", "config", "--global", "core.quotepath", "false").Run()
}

// AppPath returns the absolute path of the application's binary.
func AppPath() string {
	appPathOnce.Do(func() {
		var err error
		appPath, err = exec.LookPath(os.Args[0])
		if err != nil {
			panic("look executable path: " + err.Error())
		}

		appPath, err = filepath.Abs(appPath)
		if err != nil {
			panic("get absolute executable path: " + err.Error())
		}
	})

	return appPath
}
